import {
  ActionSheet,
  Avatar,
  Button,
  InfiniteScroll,
  NavBar,
  Skeleton,
  Toast,
} from "antd-mobile";
import { useNavigate } from "react-router-dom";
import styles from "./index.module.css";
import { MoreOutline } from "antd-mobile-icons";
import { useEffect, useState } from "react";
import request from "../../axios";

const Shop = () => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState<boolean>(false);
  const [nowInfo, setNowInfo] = useState<any>({});
  const [data, setData] = useState<any[]>([]);
  const [pageNo, setPageNo] = useState<number>(1);
  const [hasMore, setHasMore] = useState<boolean>(true);

  const actions: any[] = [
    {
      text: "查看详情",
      key: "view",
      onClick: () => {
        const currentIndex = data.findIndex(item => item.id === nowInfo.id);
        const dishListParam = encodeURIComponent(JSON.stringify(data));
        navigate(`/dish/viewer?dishList=${dishListParam}&index=${currentIndex}`);
        setVisible(false);
      },
    },
    {
      text: "编辑菜谱",
      key: "edit",
      onClick: () => {
        navigate(`/cook/edit?type=edit&info=${JSON.stringify(nowInfo)}`);
      },
    },
    {
      text: "删除菜谱",
      key: "delete",
      onClick: async () => {
        try {
          await request.delete(`/dish/delete/${nowInfo.id}`);
          Toast.show("删除成功");
        } catch (error) {
        } finally {
          getDataList(1);
          setVisible(false);
        }
      },
    },
  ];

  // 加载更多数据
  const loadMore = async () => {
    await getDataList(pageNo);
    setPageNo((prev) => prev + 1);
  };

  const getDataList = async (page: number = 1) => {
    const { data } = await request.get("/dish/list", {
      pageNo: page,
      pageSize: 10,
    });
    if (data) {
      if (page === 1) {
        setData(data?.records || []);
      } else {
        setData((prev) => [...prev, ...(data?.records || [])]);
      }
      // 更新是否有更多数据
      setHasMore(data?.records?.length >= 10 && (data?.total || 0) > page * 10);
    }
  };

  useEffect(() => {
    getDataList(1);
  }, []);

  return (
    <div className="detail" style={{ background: "rgb(242,244,247)" }}>
      <NavBar
        onBack={() => {
          navigate(-1);
        }}
      >
        菜谱管理
      </NavBar>
      <div className={styles.content}>
        {data?.map((item: any, ind: number) => {
          const type = item?.status ? "center_title" : "center_title1";
          return (
            <div className={styles.shop_item}>
              <div className={styles.top_title}>
                <div className={styles.title_left}>
                  <Avatar
                    src=""
                    style={{ "--size": "48px", borderRadius: "50%" }}
                  />
                  <span>{item?.name}</span>
                </div>
                <MoreOutline
                  fontSize={20}
                  onClick={() => {
                    setNowInfo(item);
                    setVisible(true);
                  }}
                />
              </div>
              <div className={styles.center}>
                <div className={styles[`${type}`]}>
                  ● {item?.status ? "启用中" : "停用中"}
                </div>
                <span>ID：{item?.id || "-"}</span>
              </div>
            </div>
          );
        })}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
      <div className={styles.bottom}>
        <Button
          className={styles.subbtn}
          onClick={() => navigate(`/cook/edit?type=add`)}
        >
          添加菜谱
        </Button>
      </div>
      {/* <Skeleton.Paragraph lineCount={5} animated /> */}
      <ActionSheet
        extra="请选择你要进行的操作"
        cancelText="取消"
        visible={visible}
        actions={actions}
        onClose={() => setVisible(false)}
      />
    </div>
  );
};

export default Shop;
